package com.jikangjun.disk.login.control;

import com.jikangjun.disk.util.CaptchaUtil;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/login")
public class LoginControl {

    @Resource
    private HttpSession httpSession;

    @RequestMapping("/login")
    public String loginPage(){
        httpSession.setAttribute("lang", LocaleContextHolder.getLocale().toString());

        return  "login/loginPage";
    }

    @RequestMapping("/main")
    public String mainPage(){
        return  "redirect:/";
    }

    /**
     * 处理登录验证
     */
    @RequestMapping(value = "/verification", method = RequestMethod.POST)
    public String verifyLogin(@RequestParam String username, 
                            @RequestParam String password,
                            @RequestParam String captcha,
                            HttpSession session,
                            Model model) {
        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            model.addAttribute("error", "验证码错误");
            return "login/loginPage";
        }

        // TODO: 这里添加实际的用户验证逻辑
        // 验证用户名和密码
        
        // 验证通过后重定向到主页
        return "redirect:/login/main";
    }

    /**
     * 生成验证码图片
     */
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response, HttpSession session) {
        // 设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Expires", "0");
        
        try (OutputStream outputStream = response.getOutputStream()) {
            // 生成验证码并写入响应
            String captchaText = CaptchaUtil.generateCaptcha(outputStream);
            
            // 将验证码文本存入session
            session.setAttribute("captcha", captchaText);
        } catch (IOException e) {
            // 记录错误日志
            System.err.println("验证码生成失败: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
